<template>
  <div id="user-settings">
    <!--筛选区域-->
    <GeneralFilter
        v-bind="filterOption"
        ref="filter"
        @searchEvent="searchEvent"
        @clearEvent="clearEvent">
    </GeneralFilter>

    <!-- 筛选区间列表 -->
    <ScreenLabel
        :setionFilterArr="setionFilterArr"
        @upDateFilter="upDateFilter"/>

    <div>
      <!--注册按钮-->
      <el-button
          type="primary"
          icon="el-icon-plus"
          @click="$refs.addDialog.show();$emit('addEvent')">
        {{'添加' + title}}
      </el-button>


      <el-button
          id="my-refreshBtn"
          style="float: right"
          type="success"
          icon="el-icon-refresh"
          @click="refreshTable()">
        刷新表格</el-button>

      <!--预留按钮拓展-->
      <slot name="btnExpand"></slot>
    </div>

    <!--注册弹出表单-->
    <AddDialog
        v-bind="addDialogOption"
        :title="title"
        ref="addDialog"
        @addSuccessEvent="paramChange()"
    >
    </AddDialog>

    <!--表格-->
    <BomTable
        ref="table"
        v-bind="tableOption"
        :filterTableData="filterTable"
        @updateEvent="updateEvent"
        @deleteEvent="deleteEvent"
        @changeTableData="changeTableData(arguments)"
        @selectionChangeEvent="selectionChange"
        @sortChangeEvent="sortChangeEvent"></BomTable>

    <!--修改弹出表单-->
    <UpdateDialog
        v-bind="updateDialogOption"
        :title="title"
        ref="updateDialog"
        @updateSuccessEvent="paramChange()"
    ></UpdateDialog>

    <!--分页组件-->
    <GeneralPage
        ref="page"
        @changeEvent="paramChange">
    </GeneralPage>
  </div>
</template>

<script>
import GeneralFilter from "@/components/GeneralEditTable/FilterComponent/GeneralFilter";
import AddDialog from "@/components/GeneralEditTable/DialogComponent/AddDialog";
import BomTable from "@/components/GeneralEditTable/TableComponent/Bom-Table";
import GeneralPage from "@/components/GeneralEditTable/PageComponent/GeneralPage";
import UpdateDialog from "@/components/GeneralEditTable/DialogComponent/UpdateDialog";
import ScreenLabel from "@/components/SectionScreen/screenLabel";

export default {
  name: 'Bom-EditTable',
  components: {UpdateDialog, GeneralPage, BomTable, AddDialog, GeneralFilter,ScreenLabel},
  data() {
    return {
      setionFilterArr:[], // 筛选条件数组
      // 表格多选的值
      selectionValue: '',

      // 排序数据
      sort: 'id',
      order: 'asc',

      // 防抖函数计时器
      timer: null,
    }
  },
  props: {
    // 增删改查api
    title: String,
    getApi: Function,
    deleteApi: Function,

    // 配置信息
    filterOption: Object,
    addDialogOption: Object,
    tableOption: Object,
    updateDialogOption: Object,

    // 账号筛选
    reportDate: Object,
    // 时间筛选
    bomSearchData: Object,

    // 列表请求函数
    getListFunction: Array,

  },
  methods: {
    // 获取表格列表
    getList(param,otherParam) {
      let other = {...this.bomSearchData}
      if (this.reportDate.date.length > 1) {
        other.start_time = this.reportDate.date[0]
        other.end_time = this.reportDate.date[1]
      }
      return this.getApi({...param,...other,is_report:1},otherParam).then(result => {
        // 设置表格数据
        this.tableOption.tableData = result[0]
        // 设置数据数量
        this.$refs.page.setTotalNum(result[1])
        // 给刷新功能确认状态
        return Promise.resolve()
      }).catch(err => {
        this.$message({
          type: 'error',
          message: '请求列表失败！+\n' + err.msg
        })
        console.error(err)
        // 给刷新功能确认状态
        return Promise.reject()
      })
    },
    // 搜索函数
    searchEvent() {
      // 回到第一页
      this.$refs.page.setPage(1)
      this.paramChange()
    },
    // 筛选区域清空
    clearEvent() {
      // 回到第一页
      this.$refs.page.setPage(1)
      // 刷新数据
      this.paramChange()
    },
    //  表格数据更新
    refreshTable() {
      let loading = this.$loading({
        lock: true,
        text: '刷新中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      // 重置分页组件数据
      this.$refs.page.currentChange(1,false)
      // 重置表格排序
      this.$refs.table.$children[0].clearSort()

      // 刷新重新请求数据
      this.getList( {...this.$refs.filter.getData(),...this.$refs.page.getPage(), ...this.bomSearchData, sort: this.sort, order: this.order, refresh: 1}).then(() => {
        loading.close()
      })
      this.selectionValue = ''
    },
    // 根据当前搜索词、页数等参数请求数据
    paramChange() {
      this.getList( {...this.$refs.filter.getData(),...this.$refs.page.getPage(), ...this.bomSearchData, sort: this.sort, order: this.order})
      this.selectionValue = ''
    },
    // 返回当前所有筛选条件
    getParam() {
      let obj = {...this.$refs.filter.getData(),...this.$refs.page.getPage(), ...this.bomSearchData, sort: this.sort, order: this.order}
      if (this.reportDate.date.length > 1) {
        obj.start_time = this.reportDate.date[0]
        obj.end_time = this.reportDate.date[1]
      }
      return obj
    },
    // 修改按钮点击
    updateEvent(row) {
      this.$refs.updateDialog.show(row)
      this.$emit('updateEvent')
    },
    // 删除点击
    deleteEvent(row) {
      this.$confirm('此操作将永久删除该条'+ this.title +', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteApi(row).then(() => {
          this.$notify({
            title: '成功',
            type: "success",
            message: '删除' + this.title + '成功'
          })
          this.paramChange()
        }).catch(error => {
          this.$notify({
            title: '失败',
            type: "error",
            message: '删除' + this.title + '失败\n' + error
          })
          console.error(error)
        })
      })
    },
    // 遍历获取列表函数(筛选、添加、更新的下拉框数据更新)
    traverseGetList() {
      for (let item of this.getListFunction) item()
    },
    changeTableData(setionData) {
      let colProperty = setionData[0]
      let sectionLeft = setionData[1]
      let sectionRight = setionData[2]
      let labelName = setionData[3]
      let isRepeat = 0
      this.setionFilterArr.map(item => {
        if (item.colProperty == colProperty){
          isRepeat = 1
          item.sectionLeft = sectionLeft
          item.sectionRight = sectionRight
        }
      })
      if (isRepeat == 0){
        this.setionFilterArr.push({
          colProperty,sectionLeft,sectionRight,labelName
        })
      }
    },
    // 更新筛选条件
    upDateFilter(index){
      this.setionFilterArr.splice(index,1)
    },

    // 表格多选触发事件
    selectionChange(val) {
      this.selectionValue = val
    },
    // 排序点击事件
    sortChangeEvent(param) {
      this.sort = param.prop
      if (param.order == null) {this.order = 'asc',this.sort='id'}
      else this.order = param.order == 'ascending' ? 'asc' : 'desc'
      this.paramChange()
    },

    // 树形控件防抖函数
    debounce() {
      if (this.timer) clearTimeout(this.timer)
      let that = this
      this.timer = setTimeout(() => {
        this.paramChange()
        // 遍历下拉框组件数据
        this.traverseGetList()
      },1000)
    },
  },
  created() {
    // 获取表格列表
    if (this.bomSearchData.local_account_id || this.bomSearchData.account_id)this.getList({ ...this.bomSearchData, sort: this.sort, order: this.order,page:this.page,page_size:this.page_size})
  },
  watch: {
    // 时间组件发生变化
    reportDate: {
      handler(val) {
        // 刷新表格
        this.paramChange()
        // 遍历下拉框组件数据
        this.traverseGetList()
        for (let item of this.tableOption.columnOption) {
          if (item.type == 'Bom-OperationEditAndDelete') {
            item.show = !val.isShowReport
            this.$nextTick(() => {
              this.$refs.table.$children[0].doLayout()
            })
          }
        }
      },
      deep: true
    },
    // 监听数据变化
    bomSearchData: {
      handler() {
        // 使用防抖函数降低请求次数
        this.debounce()
      },
      deep: true,
    }
  },
  computed: {
    // 根据筛选条件过滤数据
    filterTable(){
      return this.tableOption.tableData.filter(table => {
        return this.setionFilterArr.every(filter => table[filter.colProperty] >= filter.sectionLeft && table[filter.colProperty] <= filter.sectionRight)
      })
    },
  },
}
</script>

<style scoped lang="scss">
#paging {
  display: flex;
  justify-content: center;
}
</style>
